/***********************************************************************************************************************
**	filename: main.c
**	author: Echo Zhang @2021-04-30
**  e-mail: not_xx@126.com
***********************************************************************************************************************/

#include "user_types.h"
#include "dbg.h"
#include <string.h>

static void _conv_bin_to_hfile(const char *binFileName)
{
    size_t binFileNameLen = strlen(binFileName);
    char hfileName[binFileNameLen+3];
    memcpy(hfileName, binFileName, binFileNameLen);
    memcpy(&hfileName[binFileNameLen], ".h", 3);
    
    FILE *binFile = fopen(binFileName, "r");
    if(binFile == NULL) {
        sys_err("failed to open bin file: %s", binFileName);
        return;
    }
    FILE *hFile = fopen(hfileName, "w");
    if(hFile == NULL) {
        sys_err("failed to create bin file: %s", hfileName);  
        goto __label_end2;  
    }
    char buffer[16];
    int i, bufferLen;
    fprintf(hFile, "static const ui8 %s[] = {", binFileName);
    while(!feof(binFile)) {
        bufferLen = fread(buffer, 1, sizeof(buffer), binFile);
        if(bufferLen < 0) {
            sys_err("failed to read bin file: %s", binFileName);
            goto __label_end1;
        }
        
        fprintf(hFile, "\n    ");
        for(i=0; i<bufferLen; i++) {
            fprintf(hFile, "0x%02hhX, ", buffer[i]);
        }
    }
    fprintf(hFile, "\n}");
    sys_msg("finish to create hfile: %s", hfileName);
__label_end1:
    fclose(hFile);
__label_end2:
    fclose(binFile);
}

int main(int argc, char *argv[])
{
    if(argc <= 1) {
        sys_msg("usage: %s binFile1 binFile2 ...", argv[0]);
        return -1;
    }
    int i;
    for(i=1; i<argc; i++) {
        _conv_bin_to_hfile(argv[i]);
    }
    return 0;
}

/***********************************************************************************************************************
**	endline
***********************************************************************************************************************/
